<template>
  <div class="api-edit p-4">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      class="bg-white p-6 rounded-lg shadow-md"
    >
      <!-- 基本信息 -->
      <div class="mb-6">
        <h2 class="text-lg font-medium mb-4">基本信息</h2>
        <el-form-item label="接口名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入接口名称" />
        </el-form-item>
        <el-form-item label="接口类型" prop="type">
          <el-select v-model="formData.type" placeholder="请选择接口类型" class="w-full">
            <el-option label="HTTP" value="HTTP" />
            <el-option label="Database" value="Database" />
            <el-option label="File" value="File" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入接口描述"
          />
        </el-form-item>
      </div>

      <!-- 运行配置 -->
      <div class="mb-6">
        <h2 class="text-lg font-medium mb-4">运行配置</h2>
        <el-form-item label="调度类型" prop="scheduleType">
          <el-select v-model="formData.scheduleType" placeholder="请选择调度类型" class="w-full">
            <el-option label="Cron表达式" value="cron" />
            <el-option label="固定频率" value="fixed" />
            <el-option label="手动触发" value="manual" />
          </el-select>
        </el-form-item>
        
        <el-form-item 
          v-if="formData.scheduleType === 'cron'"
          label="Cron表达式" 
          prop="scheduleCycle"
        >
          <el-input v-model="formData.scheduleCycle" placeholder="请输入Cron表达式">
            <template #append>
              <el-button @click="handleShowCronHelper">
                <div class="i-carbon-help mr-1"></div>帮助
              </el-button>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item 
          v-if="formData.scheduleType === 'fixed'"
          label="执行间隔" 
          prop="scheduleInterval"
        >
          <el-input-number 
            v-model="formData.scheduleInterval" 
            :min="1" 
            class="w-40"
          />
          <el-select v-model="formData.scheduleUnit" class="ml-2 w-32">
            <el-option label="分钟" value="minute" />
            <el-option label="小时" value="hour" />
            <el-option label="天" value="day" />
          </el-select>
        </el-form-item>

        <el-form-item label="超时时间" prop="timeout">
          <el-input-number 
            v-model="formData.timeout" 
            :min="1" 
            :max="1440"
            class="w-40"
          />
          <span class="ml-2 text-gray-500">分钟</span>
        </el-form-item>

        <el-form-item label="重试次数" prop="retryCount">
          <el-input-number 
            v-model="formData.retryCount" 
            :min="0" 
            :max="10"
            class="w-40"
          />
        </el-form-item>
      </div>

      <!-- 数据源配置 -->
      <div class="mb-6">
        <h2 class="text-lg font-medium mb-4">数据源配置</h2>
        <el-form-item label="数据源" prop="dataSource">
          <el-select v-model="formData.dataSource" placeholder="请选择数据源" class="w-full">
            <el-option label="CRM系统" value="crm" />
            <el-option label="ERP系统" value="erp" />
            <el-option label="OA系统" value="oa" />
          </el-select>
        </el-form-item>

        <el-form-item label="目标库" prop="targetDb">
          <el-select v-model="formData.targetDb" placeholder="请选择目标库" class="w-full">
            <el-option label="数据仓库" value="dw" />
            <el-option label="分析库" value="analysis" />
            <el-option label="备份库" value="backup" />
          </el-select>
        </el-form-item>

        <el-form-item label="SQL语句" prop="sql">
          <el-input
            v-model="formData.sql"
            type="textarea"
            :rows="5"
            placeholder="请输入SQL语句，支持使用#{lastSyncTime}等变量"
          />
        </el-form-item>
      </div>

      <!-- 操作按钮 -->
      <div class="flex justify-center space-x-4">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          {{ isEdit ? '保存' : '创建' }}
        </el-button>
      </div>
    </el-form>

    <!-- Cron表达式帮助弹窗 -->
    <el-dialog
      v-model="showCronHelper"
      title="Cron表达式帮助"
      width="600px"
    >
      <div class="cron-helper">
        <h3 class="font-medium mb-2">常用示例：</h3>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="每天凌晨1点">0 0 1 * * ?</el-descriptions-item>
          <el-descriptions-item label="每小时执行">0 0 * * * ?</el-descriptions-item>
          <el-descriptions-item label="每5分钟执行">0 */5 * * * ?</el-descriptions-item>
          <el-descriptions-item label="每周一凌晨2点">0 0 2 ? * MON</el-descriptions-item>
          <el-descriptions-item label="每月1号凌晨3点">0 0 3 1 * ?</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'

const props = defineProps<{
  isEdit?: boolean
  apiId?: number
}>()

// 表单引用
const formRef = ref<FormInstance>()

// 加载状态
const loading = ref(false)

// Cron帮助弹窗
const showCronHelper = ref(false)

// 表单数据
const formData = reactive({
  name: '',
  type: '',
  description: '',
  scheduleType: 'cron',
  scheduleCycle: '',
  scheduleInterval: 1,
  scheduleUnit: 'hour',
  timeout: 30,
  retryCount: 3,
  dataSource: '',
  targetDb: '',
  sql: ''
})

// 表单校验规则
const formRules = {
  name: [
    { required: true, message: '请输入接口名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择接口类型', trigger: 'change' }
  ],
  description: [
    { max: 200, message: '不能超过200个字符', trigger: 'blur' }
  ],
  scheduleType: [
    { required: true, message: '请选择调度类型', trigger: 'change' }
  ],
  scheduleCycle: [
    { 
      required: true, 
      message: '请输入Cron表达式', 
      trigger: 'blur',
      validator: (_: any, value: string) => {
        if (!value && formData.scheduleType === 'cron') {
          return false
        }
        return true
      }
    }
  ],
  timeout: [
    { required: true, message: '请设置超时时间', trigger: 'blur' }
  ],
  dataSource: [
    { required: true, message: '请选择数据源', trigger: 'change' }
  ],
  targetDb: [
    { required: true, message: '请选择目标库', trigger: 'change' }
  ],
  sql: [
    { required: true, message: '请输入SQL语句', trigger: 'blur' }
  ]
}

// 显示Cron帮助
const handleShowCronHelper = () => {
  showCronHelper.value = true
}

// 取消
const handleCancel = () => {
  ElMessage.info('取消操作')
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    // TODO: 调用后端API保存数据
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success(`${props.isEdit ? '保存' : '创建'}成功`)
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    loading.value = false
  }
}

// 如果是编辑模式，加载接口数据
if (props.isEdit && props.apiId) {
  // TODO: 调用后端API获取接口详情
  loading.value = true
  setTimeout(() => {
    Object.assign(formData, {
      name: '用户数据同步',
      type: 'Database',
      description: '从CRM系统同步用户数据到数据仓库',
      scheduleType: 'cron',
      scheduleCycle: '0 0 1 * * ?',
      timeout: 30,
      retryCount: 3,
      dataSource: 'crm',
      targetDb: 'dw',
      sql: 'SELECT * FROM users WHERE update_time > #{lastSyncTime}'
    })
    loading.value = false
  }, 1000)
}
</script>

<style scoped lang="scss">
.api-edit {
  :deep(.el-form-item__label) {
    font-weight: 500;
  }
}
</style> 